// 状态主要有： Pending/Fulfilled/Rejected
const STATE = {
	PENDING: 'Pending',
	FULLFILLED: 'Fulfilled',
	REJECTED: 'Rejected'
}

function Promisep(executor) {
   var _this = this;
   this.status = STATE.PENDING;
   this.value = undefined; //成功结果
   this.reason = undefined; //失败原因
   this.resolvedCallBacks = [];
	 this.rejectedCallBacks = [];
	 this.then = then;

   function then(onFullfilled, onRejected) {
		 console.log("_this.status", this.status, _this.value);
     if (_this.status == STATE.FULLFILLED) {
       onFullfilled(_this.value);
     }
     if (_this.status == STATE.REJECTED) {
       onRejected(_this.reason);
     }
     if (_this.status == STATE.PENDING) {
       onFullfilled && _this.resolvedCallBacks.push(onFullfilled);
       onRejected && _this.rejectedCallBacks.push(onRejected);
     }
   }

   function _handleCallBacks(callBacks) {
     callBacks.forEach(callBack => {
       if (_this.status == STATE.FULLFILLED) {
         typeof callBack === "function" && callBack(_this.value);
       } else {
         typeof callBack === "function" && callBack(_this.reason);
       }
     });
   }

   function _resolve(value) {
		 console.log("resolve", value, _this.resolvedCallBacks, _this.status);
     if (_this.status == STATE.PENDING) {
       _this.status = STATE.FULLFILLED;
       _this.value = value;
       _handleCallBacks(_this.resolvedCallBacks);
		 }

   }

   function _reject(reason) {
     if (_this.status == STATE.PENDING) {
       _this.status = STATE.REJECTED;
       _this.reason = reason;
       _handleCallBacks(_this.rejectedCallBacks);
     }
	 }
	 
	//  Promisep.prototype.then = function(onFullfilled, onRejected) {
  //    if (this.status == STATE.FULLFILLED) {
  //      onFullfilled(this.value);
  //    }
  //    if (this.status == STATE.REJECTED) {
  //      onRejected(this.reason);
  //    }
  //    if (this.status == STATE.PENDING) {
  //      onFullfilled && this.resolvedCallBacks.push(onFullfilled);
  //      onRejected && this.rejectedCallBacks.push(onRejected);
  //    }
  //  };

   try {
     typeof executor === 'function' && executor(_resolve, _reject);
   } catch (error) {
     _reject(error);
	 }

	 return _this;
	 
 }



module.exports = Promisep;
